package initialition

import (
	"fmt"
	"github.com/3.27/global"
	"github.com/3.27/internal/model/dao"
	"github.com/go-redis/redis"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"os"
)

func init() {
	ZapInit()
	ConfigInit()
	DBInit()
	RdbInit()
}

func ZapInit() {
	os.MkdirAll("./log", 0777)
	config := zap.NewDevelopmentConfig()
	config.OutputPaths = []string{
		"./log/log",
	}
	build, _ := config.Build()
	zap.ReplaceGlobals(build)
}
func ConfigInit() {

	viper.SetConfigFile("./config/dev.yaml")
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
	viper.Unmarshal(&global.GlobalConfig)
	fmt.Println("解析配置", global.GlobalConfig)
}

func DBInit() {
	var err error
	config := global.GlobalConfig.Mysql
	dsn := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", config.UserName, config.Password, config.Host, config.Port, config.Database)
	global.DB, err = gorm.Open(mysql.Open(dsn))
	if err != nil {
		panic(err)
	}
	fmt.Println("mysql connect successful!")
	global.DB.AutoMigrate(&dao.User{}, &dao.Order{}, &dao.Hotel{}, &dao.HotelRoom{})
}
func RdbInit() {
	config := global.GlobalConfig.Redis
	global.Rdb = redis.NewClient(&redis.Options{
		Addr:     config.Host,
		Password: config.Password,
	})
	err := global.Rdb.Ping().Err()
	if err != nil {
		panic(err)
	}
	fmt.Println("redis connect successful!")
}
